from . import app
from flask import request
import telebot
from configparser import ConfigParser
import logging

logging.basicConfig(level=logging.INFO)

class Config:
    def __init__(self, config_path='config.ini'):
        self.config = ConfigParser()
        self.config.read(config_path)

    def get_section(self, section):
        if self.config.has_section(section):
            return {k: v for k, v in self.config.items(section)}
        else:
            raise Exception(f"Section {section} not found in the configuration file.")

# Загрузка конфигурации
config_path = 'config.ini'
config = Config(config_path)
zont_settings = config.get_section('TELEGRAM')

TOKEN = zont_settings['token']
bot = telebot.TeleBot(TOKEN)

webhook_url = '/webhook/' + TOKEN
print(f'Your webhook url is: {webhook_url}')

@app.route(webhook_url, methods=['POST'])
def telegram_webhook():
    if request.headers.get('content-type') == 'application/json':
        json_string = request.get_data(as_text=True)
        logging.info(f"Received JSON: {json_string}")
        update = telebot.types.Update.de_json(json_string)
        bot.process_new_updates([update])
        return 'Update processed'
    else:
        return 'Invalid content type', 415

@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
    logging.info(f"Received command from {message.from_user.username}: {message.text}")
    response = bot.reply_to(message, "Привет! Я твой Telegram бот.")
    logging.info(f"Sent response to {message.chat.id}: 'Привет! Я твой Telegram бот.'")